import { asyncLocalRequest } from "@/db/db";
import { Table } from "dexie";
import { ElMessage } from "element-plus";
import { ref } from "vue";

export const useTerminalAsync = (db: Table, request: Function, table?: any) => {
  const asyncLoading = ref(false);
  const asyncHandle = async () => {
    try {
      asyncLoading.value = true;
      const data = await asyncLocalRequest(db);
      if (data.length === 0) {
        ElMessage.error("没有需要同步的数据");
        asyncLoading.value = false;
        return;
      }
      // TODO:改为血球同步接口
      const result: any = await request({
        data: data.map((item) => {
          item.data_id = item.id;
          delete item.id;
          return item;
        }),
      });
      ElMessage.closeAll();
      if (result.successes.length) {
        ElMessage.success("同步成功:" + result.successes.length + "条数据");
      } else if (result.fails.length) {
        ElMessage.error("同步失败:" + result.fails.length + "条数据");
      }
      if (result.successes.length) {
        result.successes.map(async (item) => {
          await db.update(item.data_id, { synchronous: 1 });
        });
        if (table && table.reload) {
          table.reload();
        }
      }
    } finally {
      asyncLoading.value = false;
    }
  };
  return {
    asyncLoading,
    asyncHandle,
  };
};
